//
//  FZRefreshTokenService.m
//  Pods
//
//  Created by huyanming on 15/8/20.
//
//

#import "FZRefreshTokenService.h"
#import "SRAPICreater.h"
#import "SRNetWorkManager.h"

/**
 *  过期登录，发送通知
 */
NSString *const kPostLogoutNotification = @"kPostLogoutNotification";

@interface FZRefreshTokenService()

@property(assign, nonatomic)BOOL refreshing;

@end

@implementation FZRefreshTokenService

+(instancetype)shareService{
    static FZRefreshTokenService *stance;
    static dispatch_once_t once_t;
    dispatch_once(&once_t, ^{
        stance = [[FZRefreshTokenService alloc] init];
    });
    return stance;
}

-(void)changeAcessTokenWithRefreshToken:(NSString *)refreshToken successBlock:(void(^)(id responseObject))successBlock failBlock:(void (^)( id responseObject, NSError * error))failBlock
{
    if (!refreshToken || self.refreshing) {
        return ;
    }
    
    self.refreshing = YES;
    NSMutableDictionary * dic=[NSMutableDictionary dictionaryWithCapacity:2];
    [dic setValue:refreshToken forKey:@"refresh_token"];
    [dic setValue:[SRLoginUser userID] forKey:@"uid"];
    
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_refreshToken"];
    SRNetWorkManager *manager = [SRNetWorkManager sharedInstance];
    [manager POSTNODefaultParamWithUrl:urlString parameters:dic responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
            NSDictionary* dataDic = dataObject;
            if ((statusCode == 1)&&dataDic) {
                NSString* token = [dataDic objectForKey:@"auth_token"];
                NSString* exprietimeStr = [dataDic objectForKey:@"endtime"];
                NSString* refreshtoken = [dataDic objectForKey:@"refresh_token"];
                [SRLoginUser setAuthToken:token];
                [SRLoginUser setRefreshToken:refreshtoken];
                [SRLoginUser setAuthTokenExpire:exprietimeStr];
                
                NSString *upload_token = [dataDic objectForKey:@"upload_token"];
                NSString *picture_token = [dataDic objectForKey:@"picture_token"];
                
                [SRLoginUser setUploadToken:upload_token];
                [SRLoginUser setUploadPicToken:picture_token];
                
                successBlock(nil);
            }
            else if (statusCode == 0) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kPostLogoutNotification object:message userInfo:nil];
            }
            self.refreshing = NO;
        
    } failure:^(id responseObject, NSError *error) {
        failBlock(nil,nil);
        self.refreshing = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:kPostLogoutNotification object:@"认证过期，请重新登录" userInfo:nil];
    }];
}

@end
